use std::io::{self, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;

fn main() {
    // 持续读取端口号直到获得有效值
    let port = loop {
        let mut input = String::new();
        println!("Input port(1-65535):");
        
        match io::stdin().read_line(&mut input) {
            Ok(_) => {
                // 尝试解析端口号
                match input.trim().parse::<u16>() {
                    Ok(port) if port > 0 => break port, // 有效端口，退出循环
                    Ok(_) => println!("Port must be greater than 0"),
                    Err(_) => println!("Invalid port")
                }
            }
            Err(e) => println!("Failed to read {}", e)
        }
    };

    // 创建TCP监听器，监听0.0.0.0:port
    let addr = format!("0.0.0.0:{}", port);
    let listener = TcpListener::bind(addr.clone())
        .expect(&format!("Failed to listen, addr: {}", addr));
    println!("Listening, 0.0.0.0:{}", port);

    // 接受并处理连接
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                // 为每个连接创建新线程处理
                thread::spawn(|| {
                    if let Err(e) = handle_client(stream) {
                        println!("Failed to handle request: {}", e)
                    }
                });
            }
            Err(e) => {
                println!("Failed to accept connection: {}", e);
            }
        }
    }
}

// 处理客户端请求
fn handle_client(mut stream: TcpStream) -> io::Result<()> {
    // 读取请求数据
    let mut buffer = [0; 1024];
    let bytes_read = stream.read(&mut buffer)?;
    
    // 打印请求信息
    let request = String::from_utf8_lossy(&buffer[..bytes_read]);
    println!("\nGot request:\n{}", request);

    // 构建HTTP响应
    let response = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
    
    // 发送响应
    stream.write_all(response.as_bytes())?;
    stream.flush()?;
    
    Ok(())
}